package com.orangelife.mobile.parkingcard.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.TimeUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.ConfirmOrderURL;
import com.orangelife.mobile.constants.ParkingCardURL;
import com.orangelife.mobile.pay.activity.UsersPaidActivity;
import com.orangelife.mobile.pay.biz.PaymentModule;
import com.orangelife.mobile.parkingcard.adapter.GridViewLongTimeAdapter;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 停车卡缴费
 *
 * @author Administrator
 */
public class ParkingCardFeeActivity extends OrangeLifeBaseActivity implements OnClickListener {
    /** 标题栏标题 */
    private TextView tvTitle;
    /** 车牌号 */
    private TextView tvCarNumber;
    /** 停车场类型 */
    private TextView tvParkingType;
    /** 缴费时长 */
    private GridView gvLongTime;
    /** 选择抵用 */
    private LinearLayout llVoucher;
    /** 有效期 */
    private LinearLayout llPeriodValidity;
    private TextView tvPeriodValidity;
    /** 分割线 */
    private View viewPeriodValidity;
    /** 缴费金额 */
    private LinearLayout llPayMoney;
    private TextView tvPayMoney;
    /** 抵用张数 */
    private TextView tvVoucherContent;
    /** 抵用金额 */
    private TextView tvPayVoucher;
    /** 总金额 */
    private TextView tvPayPrice;
    /** 确认支付 */
    private TextView tvPay;
    /** 缴费时长适配器 */
    private GridViewLongTimeAdapter<Map<String, Object>> adapter;
    private Map<String, Object> mapIntent;
    /** 缴费时长数据 */
    private List<Map<String, Object>> listType;
    /** 停车卡是否已激活(0:未激活,1:已激活) */
    private String status;
    /** 停车卡失效日期 */
    private String time;
    private static final int LONGTIME = 1;
    private static final int PAY = 0;
    private static final int CODE = 2;
    private static final int DETEIL = 3;
    private boolean isChecked = true;
    private int curPosition;
    private String couponID;
    private String price;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parking_card_fee);
        initView();
        setText();
        setGridViewAdapter();
        setGridViewItemListener();
        getValidity();
    }

    private void getValidity() {
        HashMap<String, String> map = new HashMap<>();
        map.put("{cardID}", String.valueOf(mapIntent.get("cardsID")));
        VolleyHttpUtil.getInstance().getWithCallback(ParkingCardURL.PARKCARD_DETAIL, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                Map<String, Object> mapDetail = OrangeDataHandler.getMapWithEntityNoGson(jsonObject);
                status = mapDetail.get("status").toString();
                time = mapDetail.get("expiration_time").toString();
                feeLongTimeRequest();
            }
        });
    }

    private void feeLongTimeRequest() {
        showDialog(ParkingCardFeeActivity.this);
        HashMap<String, String> map = new HashMap<>();
        map.put("park_id", String.valueOf(mapIntent.get("parkID")));
        String currTime = TimeUtil.timeStampToDate(System.currentTimeMillis(), "yyyy-MM-dd");
        if (status.equals("0")) {/**未激活*/
            map.put("expiration_time", StringUtil.encode(currTime));
        } else if (status.equals("1")) {/**已激活*/
            map.put("expiration_time", TimeUtil.setTime(time));
        }
        VolleyHttpUtil.getInstance().getWithCallback(ParkingCardURL.PARKCARD_LONG_TIME, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {

                listType = OrangeDataHandler.getListFromJson(jsonObject, "pageEntity", null, adapter, dialog);
                if (listType.size() > 0) {
                    setValidityText();
                } else {
//					tvPay.setVisibility(View.GONE);
                    tvPay.setEnabled(false);
                    tvPay.setBackgroundResource(R.drawable.shape_btn_gray);
                }
                getVoucherRequest(0);
            }
        });
    }

    @SuppressWarnings("unchecked")
    private void setGridViewAdapter() {
        listType = new ArrayList<>();
        adapter = new GridViewLongTimeAdapter<>(this, listType);
        adapter.setSeclection(curPosition);
        gvLongTime.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    private void setGridViewItemListener() {
        gvLongTime.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                /* 是否点击的是上次位置*/
                if (curPosition == position) {
                    isChecked = false;
                } else {
                    getVoucherRequest(position);
                }
                adapter.setSeclection(position);
                curPosition = position;
                setValidityText();
                adapter.notifyDataSetChanged();
            }
        });
    }

    @SuppressWarnings("unchecked")
    private void setText() {
        tvTitle.setText(getString(R.string.park_card_pay));
        mapIntent = (Map<String, Object>) getIntent().getExtras().getSerializable("map");
        tvCarNumber.setText(mapIntent.get("carNumber").toString());
        tvParkingType.setText(mapIntent.get("parkingType").toString());
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvCarNumber = (TextView) findViewById(R.id.tvCarNumber);
        tvParkingType = (TextView) findViewById(R.id.tvParkingType);
        tvPayMoney = (TextView) findViewById(R.id.tvPayMoney);
        tvVoucherContent = (TextView) findViewById(R.id.tvVoucherContent);
        tvPeriodValidity = (TextView) findViewById(R.id.tvPeriodValidity);
        tvPayVoucher = (TextView) findViewById(R.id.tvPayVoucher);
        tvPay = (TextView) findViewById(R.id.tvPay);
        tvPayPrice = (TextView) findViewById(R.id.tvPayPrice);
        gvLongTime = (GridView) findViewById(R.id.gvLongTime);
        viewPeriodValidity = findViewById(R.id.viewPeriodValidity);
        llVoucher = (LinearLayout) findViewById(R.id.llVoucher);
        llPeriodValidity = (LinearLayout) findViewById(R.id.llPeriodValidity);
        llPayMoney = (LinearLayout) findViewById(R.id.llPayMoney);
        llVoucher.setOnClickListener(this);
        tvPay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llVoucher:
                ToastHelper.getInstance()._toast("目前暂不支持使用抵用券");
                break;
            case R.id.tvPay:
                showDialog(ParkingCardFeeActivity.this);
                HashMap<String, Object> map = new HashMap<>();
                map.put("cardsID", String.valueOf(mapIntent.get("cardsID")));
                if (listType.size() > 0) {
                    map.put("feeID", String.valueOf(listType.get(curPosition).get("id")));
                }
                map.put("totalCost", price);
                map.put("couponID", couponID);
                VolleyHttpUtil.getInstance().postWithCallback(ConfirmOrderURL.PARKCARD_PAY, map, new VolleyHttpUtil.ResponseCallBack() {
                    @Override
                    public void handleResponse(JSONObject jsonObject, int i) {
                        startActivityForPaid(String.valueOf(jsonObject));
                    }
                });
                break;
            default:
                break;
        }
    }

    /** 抵用请求 */
    private void getVoucherRequest(int position) {
        if (listType.size() > 0) {
            price = listType.get(position).get("actual_price").toString();
        }
    }

    /**
     * 设置有效期
     */
    private void setValidityText() {
        if (status.equals("0")) {/*未激活*/
            tvPeriodValidity.setText(TimeUtil.timeStampToDate(System.currentTimeMillis(), "yyyy-MM-dd") + "至" + TimeUtil.timeStampToDate(Long.valueOf(listType.get(curPosition).get("time").toString()), "yyyy-MM-dd"));
        } else if (status.equals("1")) {/*已激活*/
            tvPeriodValidity.setText(TimeUtil.setTime(time) + "至" + TimeUtil.timeStampToDate(String.valueOf(listType.get(curPosition).get("time")), "yyyy-MM-dd"));
        }
        CurryApplication.getInstance().setValidity(tvPeriodValidity.getText().toString());
        price = String.valueOf(listType.get(curPosition).get("actual_price"));
        tvPayPrice.setText(Constant.RMB_FLAG + price);
        tvPayMoney.setText(Constant.RMB_FLAG + price);
    }

    private void startActivityForPaid(String msg) {
        @SuppressWarnings("unchecked")
        Map<String, Object> mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                msg).get("entity");
        ExitApplication.getInstance().addPaidActivity(ParkingCardFeeActivity.this);
        Bundle bundle = new Bundle();
        extract(bundle, mapDetail);
        IntentHelper.getInstances().bundleWithBundleForResult(ParkingCardFeeActivity.this, UsersPaidActivity.class, bundle, 1);
    }

    private void extract(Bundle bundle, Map<String, Object> mapDetail) {
        bundle.putString("totalCost", String.valueOf(mapDetail.get("totalCost")));
        bundle.putString("couponCost", String.valueOf(mapDetail.get("couponCost")));
        bundle.putString("outtradeno", String.valueOf(mapDetail.get("outtradeno")));
        bundle.putString("orderType", String.valueOf(mapDetail.get("orderType")));
        bundle.putString("orderInfo", String.valueOf(mapDetail.get("orderContent")));
        bundle.putString("orderType", String.valueOf(mapDetail.get("orderType")));
        bundle.putString("totalPrice", Constant.RMB_FLAG + String.valueOf(mapDetail.get("totalCost")));
        bundle.putString("status", "pays");
        bundle.putString(PaymentModule.PAID_METHOD, PaymentModule.mode[5]);
    }

    @SuppressLint("ResourceAsColor")
    protected void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CODE) {
            }
        }
    }
}
